package com.zzedu.integration.lbs.impl;

import com.alibaba.fastjson2.JSON;
import com.zzedu.integration.lbs.IIpResolveServiceClient;
import com.zzedu.integration.lbs.config.IpResolveConfig;
import com.zzedu.integration.lbs.dto.IpLocationDTO;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * IP位置解析服务
 */
@Component
public class IpResolveServiceClientImpl implements IIpResolveServiceClient {

    private static final Logger log = LoggerFactory.getLogger(IpResolveServiceClientImpl.class);

    @Autowired
    IpResolveConfig ipResolveConfig;


    /**
     * 缓存名称
     */
    final String cacheName = "IP_INFO_CACHE";

    /**
     * 解析IP 对应地址服务
     *
     * @param ip
     * @return
     */
    @Override
    @Cacheable(value = cacheName, key = "#p0")
    public IpLocationDTO getRealAddressByIP(String ip) {
        log.info("对ip:{}进行定位解析", ip);
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .callTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        String realURL = ipResolveConfig.getUrl().replace("#ip#", ip);
        // 发送请求并获取响应
        try (Response response = okHttpClient.newCall(new Request.Builder()
                .url(realURL)
                .build()).execute()) {
            if (!response.isSuccessful()) {
                log.error("高德API请求失败: " + response.code() + " " + response.message());
                throw new IOException("高德API请求失败: " + response.code() + " " + response.message());
            }
            String responseBody = response.body().string();
            if (responseBody == null || responseBody.isEmpty()) {
                log.error("高德API返回空响应");
                throw new IOException("高德API返回空响应");
            }
            log.info("对ip:{}进行定位解析,定位结果:{}", ip, responseBody);
            return JSON.parseObject(responseBody, IpLocationDTO.class);
        } catch (Exception e) {
            log.error("ip:{}定位解析失败,详细:{}", ip, e.getMessage());
        }
        return null;

    }
}
